<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="tname"
          :param="param"
          :tname="tname"
          :leftTreeParentId="0"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
      </template>
      <template slot="chart">
        <ChartH
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
        <!-- <i class="icon el-icon-full-screen" @click="handleFullScreen">&nbsp;全屏</i> -->
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p style="flex: none; width: 30px"></p>
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
          <p v-if="tableData.content.length>0" style="flex: none; width: 100px">
            <span class="merge-btn" @click="handleMerge">合并</span>
          </p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p style="flex: none; width: 30px">
            <el-checkbox
              v-model="checkList[index]"
              :key="index"
              @change="handleChangeCheck"
              >&nbsp;</el-checkbox
            >
          </p>
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item.data" :key="j">
            <span v-if="!tableData.inputRefs[index][j]">{{ ite }}</span>
            <span v-else>
              <el-input
                v-model="tableData._content[index]['data'][j]"
                placeholder=""
                size="mini"
                :style="{'min-width': tableData._content[index]['data'][j].length >= 10 ? '230px' : '100px'}"
              ></el-input>
            </span>
            <span v-if="j != 1" class="tools-box">
              <!-- 修改 -->
              <i
                v-if="!tableData.inputRefs[index][j]"
                class="tools-btn el-icon-edit"
                @click="handleShowInp(index, j)"
              ></i>
              <!-- 保存 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-check"
                @click="handleUpdateIte(index, j)"
              ></i>
              <!-- 取消 -->
              <i
                v-if="tableData.inputRefs[index][j]"
                class="tools-btn el-icon-close"
                @click="handleShowInp(index, j)"
              ></i>
            </span>
          </p>
          <p style="flex: none; width: 100px">
            <el-checkbox
              v-model="item.mergeChecked"
              :key="index"
            >&nbsp;</el-checkbox>
          </p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartH from "../charts/ChartH";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry,
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object,
    },
    dcData: {
      type: Object,
    },
  },
  components: {
    CSlot,
    ChartH,
    ChooseScreen,
  },
  data() {
    return {
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      timeType: "", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      //
      chartData: [],
      chartType: "line",
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      tableData: {
        tit: [],
        content: [],
        _content: [], // 存储修改content值
        inputRefs: [], // 记录修改展示的input的值
      },
      checkList: [], // 多选框勾选数据
      mergeList: [], // 合并多选框勾选数据
      yearArr: [],
      emptyText: "数据加载中...",
      dbid: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
    };
  },
  computed: {
    ...mapState(["searchWord"]),
  },
  watch: {
    dcData(val) {
      this.tname = this.chartTempl.tname;
      this.chartData = val.chartData;
      this.dbid = String(this.$route.query.type);
      this.init();
    },
  },
  mounted() {
    this.loading = true;
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      if (this.dcData && this.dcData.chartData) {
        this.loading = false;
        if (this.dbid === "patent") {
          // 专利词云分析
          this.chartData = this.repaceH5(this.dcData.chartData)
        } else if (this.dbid === "paper") {
          // 论文词云分析
          let terms = this.dcData.chartData[0].data.terms;
          let chartData = [];
          terms.map((item) => {
            chartData.push({
              key: item.t,
              doc_count: item.freq,
            });
          });
          this.chartData = this.repaceH5(chartData)
        }
        this.timeType = this.chartTempl.tdata.datefield;
        this.datefieldformat = this.chartTempl.tdata.datefieldformat;
        this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
        this.tableData.tit = ["索引", "名称", "数量"];
        this.tableData.content = [];
        this.tableData._content = [];
        this.tableData.inputRefs = [];
        this.checkList = [];
        this.chartData &&
          this.chartData.map((item) => {
            this.tableData.content.push({
              data: [item.key, Number(item.doc_count)],
              mergeChecked: false
            });
            this.tableData._content.push({
              data: [item.key, Number(item.doc_count)],
              mergeChecked: false
            });
            this.checkList.push(true);
            // 记录inputRefs
            this.tableData.inputRefs.push([false, false]);
          });
      } else if (this.dcData.chartData == null) {
        this.loading = false;
        this.emptyText = "接口无数据返回，稍后再试";
      } else {
        this.loading = true;
        this.emptyText = "数据加载中...";
      }
    },
    // 过滤h5标记
    repaceH5(arr) {
      arr.forEach(v => {
        if (v.key) {
          v.key = v.key.replace(/<base:Sub>/g, "")
            .replace(/<\/base:Sub>/g, '')
            .replace(/<base:Sup>/g, '')
            .replace(/<\/base:Sup>/g, '')
            .replace(/<sub>/g, '')
            .replace(/<\/sub>/g, '')
            .replace(/<sup>/g, '')
            .replace(/<\/sup>/g, '')
        }
      })
      return arr
    },
    // 修改表格文字内容
    handleUpdateIte(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请勾选后再进行修改",
        });
        return;
      }
      this.$set(
        this.tableData.content[index]["data"],
        j,
        this.tableData._content[index]["data"][j]
      );
      this.handleShowInp(index, j);
      // 重新设置chartData数据
      let chartData = JSON.parse(JSON.stringify(this.chartData));
      if (j == 0) {
        chartData[index]["key"] = this.tableData.content[index]["data"][j];
      } else if (j == 1) {
        chartData[index]["doc_count"] = this.tableData.content[index]["data"][j];
      }
      this.chartData = chartData;
      // 重新设置tableData数据
      this.$set(this.tableData.content[index]["data"], 0, chartData[index]["key"])
    },
    // 显隐修改表格文字input框
    handleShowInp(index, j) {
      if (!this.checkList[index]) {
        this.$message({
          type: "warning",
          message: "请选勾选后再进行修改",
        });
        return;
      }
      if (this.tableData.inputRefs[index][j] === true) {
        this.$set(this.tableData.inputRefs[index], j, false);
      } else {
        this.$set(this.tableData.inputRefs[index], j, true);
      }
    },
    // 勾选
    handleChangeCheck() {
      let chartData = JSON.parse(JSON.stringify(this.chartData));
      this.checkList.forEach((v, index) => {
        if (v === true) {
          chartData[index]["key"] = this.tableData._content[index]["data"][0];
          chartData[index]["doc_count"] = this.tableData._content[index]["data"][1];
        } else {
          chartData[index]["key"] = null;
          chartData[index]["doc_count"] = null;
        }
      });
      this.chartData = chartData;
    },
    // 合并
    handleMerge() {
      let list = this.tableData.content.filter(v => v.mergeChecked == true)
      if (list.length > 1) {
        let indexList = [];
        list.forEach((item) => {
          this.tableData.content.map((citem, index) => {
            if (citem.data[0] == item.data[0]) {
              indexList.push(index);
            }
          });
        });
        let num = 0
        for (let i = 0; i < indexList.length; i++) {
          let number = this.tableData.content[indexList[i]].data[1]
          num += number
        }
        this.tableData.content[indexList[0]].data[1] = num;
        for (let i = 1; i < list.length; i++) {
          let ind = this.tableData.content.findIndex(b => b["data"][0] === list[i].data[0])
          if (ind > -1) {
            this.tableData.content.splice(ind, 1)
          }
        }
        // 合并后处理
        this.tableData.content.forEach(v => {
          v.mergeChecked = false
        })
        let charData = []
        this.tableData.content.forEach(v => {
          let obj = this.chartData.find(b => b.key === v.data[0])
          if (obj) {
            charData.push(obj)
          }
        })
        this.chartData = charData
      } else {
        this.$message({
          type: "warning",
          message: "请至少选择两个关键词！",
        });
      }
    },
    getChartData(Params) {
      this.loading = true;
      let ths = this;
      if (this.cancel !== null) {
        this.cancel();
      }
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;

      if (this.searchWord !== "") {
        sq = `${this.searchWord} and ` + sq;
      }

      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: [],
        _content: [],
        inputRefs: [],
      };

      let aggs = [];
      if (this.dbid == "patent") {
        aggs = [{ field: "keywords", type: "keyword", size: Params.size }];
      } else if (this.dbid == "paper") {
        aggs = [
          {
            action: "trendme.GenNewTrend",
            parameters: {
              is_open: true,
              query_type: "keywords",
            },
            size: Params.size ,
          },
        ];
      }
      let params = {
        eSearch: sq,
        dbid: this.dbid,
        ipi: 1,
        ips: 0, //区分查询列表还是查询聚合数据
        aggs: aggs,
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let familyFlag = localStorage.getItem("familyFlag") || false;
      if (familyFlag ==1 ) {
        params["familyFlag"] = true; // 同族合并
        params["tzzlhb"] = false; // 同专利合并
      } else if (familyFlag ==2) {
        params["familyFlag"] = false; // 同族合并
        params["tzzlhb"] = true; // 同专利合并
      }
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        }),
      })
        .then((res) => {
          this.loading = false;
          let data = res.data;
          this.$store.commit("setTotalTxt", data.total);
          if (data) {
            this.chartData = data.chartData;
            this.tableData.tit = ["索引", "名称", "数量"];
            this.tableData.content = [];
            this.tableData._content = [];
            this.tableData.inputRefs = [];
            this.checkList = [];
            if (this.dbid === "patent") {
              // 专利词云分析
              this.chartData &&
                this.chartData.map((item) => {
                  this.tableData.content.push({
                    data: [item.key, Number(item.doc_count)],
                    mergeChecked: false
                  });
                  
                  this.tableData._content.push({
                    data: [item.key, Number(item.doc_count)],
                    mergeChecked: false
                  });
                  this.checkList.push(true);
                  // 记录inputRefs
                  this.tableData.inputRefs.push([false, false]);
                });
            } else if (this.dbid === "paper") {

              // 论文词云分析
              let term = this.dcData.chartData[0].data.terms;
              let terms = term.slice(0, Params.size);
              let chartData = [];
              terms.map((item) => {
                chartData.push({
                  key: item.t,
                  doc_count: item.freq,
                });
                this.tableData.content.push({
                  data: [item.t, item.freq],
                  mergeChecked: false
                });
                this.tableData._content.push({
                  data: [item.t, item.freq],
                  mergeChecked: false
                });
                this.checkList.push(true);
                // 记录inputRefs
                this.tableData.inputRefs.push([false, false]);
              });
              this.chartData = chartData;
            }
          } else {
            this.emptyText = "暂无数据";

            this.loading = false;
          }
        })
        .catch((err) => {
          this.emptyText = "暂无数据";

          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef
      if (!element) {
        return
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws =
        XLSX.utils.aoa_to_sheet(aoa); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    },
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  },
};
</script>

<style lang="scss" scoped>
.chart-tab {
  .chart-tab-ul {
    .merge-btn {
      padding: 1px 10px;
      border-radius: 4px;
      background-color: $mainColor;
      font-weight: bold;
      color: #fff;
      font-size: 12px;
      cursor: pointer;
    }
  }
}

</style>
